package com.onstar.cn.payme.payutil.wxpay;

import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PayMeConstants;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * 
* @ClassName: WechatUtil 
* @Description: 微信支付Util类
* @author Xiaofeng Feng
* @date 2015年9月9日 下午2:09:59
 */
public class WechatUtil {
	private static long timeStamp;
	private static String nonceStr, packageValue;

	/**
	 * 
	* @Title: genProductParams 
	* @Description: 生成微信支付请求参数
	* @param @param subject
	* @param @param notifyUrl
	* @param @param orderId
	* @param @param partnerId
	* @param @param partnerKey
	* @param @param appKey
	* @param @param money
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public static String genProductParams(String subject, String notifyUrl, String orderId, String partnerId,
			String partnerKey, String appKey, String money) {
		JSONObject json = new JSONObject();
		try {
			json.put("appid", PayMeConstants.APP_ID);
			String traceId = "onstar_" + genTimeStamp(); // traceId
			json.put("traceid", traceId);
			nonceStr = genNonceStr();
			json.put("noncestr", nonceStr);
			List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
			packageParams.add(new BasicNameValuePair("bank_type", "WX"));
			packageParams.add(new BasicNameValuePair("body", CommonUtil.removeSpecialCharacters(subject)));
			packageParams.add(new BasicNameValuePair("fee_type", "1"));
			packageParams.add(new BasicNameValuePair("input_charset", "UTF-8"));
			packageParams.add(new BasicNameValuePair("notify_url", notifyUrl));
			packageParams.add(new BasicNameValuePair("out_trade_no", orderId));
			packageParams.add(new BasicNameValuePair("partner", partnerId));
			packageParams.add(new BasicNameValuePair("spbill_create_ip", "192.168.1.1"));
			packageParams.add(new BasicNameValuePair("total_fee", money));
			packageValue = genPackage(packageParams, partnerKey);

			json.put("package", packageValue);
			timeStamp = genTimeStamp();
			json.put("timestamp", timeStamp);

			List<NameValuePair> signParams = new LinkedList<NameValuePair>();
			signParams.add(new BasicNameValuePair("appid", PayMeConstants.APP_ID));
			signParams.add(new BasicNameValuePair("appkey", appKey));
			signParams.add(new BasicNameValuePair("noncestr", nonceStr));
			signParams.add(new BasicNameValuePair("package", packageValue));
			signParams.add(new BasicNameValuePair("timestamp", String.valueOf(timeStamp)));
			signParams.add(new BasicNameValuePair("traceid", traceId));
			json.put("app_signature", genSign(signParams));
			json.put("sign_method", "sha1");
		} catch (Exception e) {
			return null;
		}
		return json.toString();
	}
	/**
	* @Title: genPackage 
	* @Description: genPackage
	* @param @param params
	* @param @param partnerKey
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	private static String genPackage(List<NameValuePair> params, String partnerKey) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(partnerKey);
		// 进行md5摘要前，params内容为原始内容，未经过url encode处理
		String packageSign = PayMD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		return URLEncodedUtils.format(params, "UTF-8") + "&sign=" + packageSign;
	}
	/**
	 * 
	* @Title: genNonceStr 
	* @Description: genNonceStr
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	private static String genNonceStr() {
		Random random = new Random();
		return PayMD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	/**
	 * 
	* @Title: genTimeStamp 
	* @Description: genTimeStamp
	* @param @return    设定文件 
	* @return long    返回类型 
	* @throws
	 */
	private static long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}
	/**
	 * 
	* @Title: genSign 
	* @Description: genSign
	* @param @param params
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public static String genSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (; i < params.size() - 1; i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append(params.get(i).getName());
		sb.append('=');
		sb.append(params.get(i).getValue());
		String sha1 = PayUtil.sha1(sb.toString());
		return sha1;
	}

}
